/*
 *  Copyright 2019-2020 Zheng Jie
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.alien.admin.modules.deploy.service.impl;

import com.alien.admin.exception.BadRequestException;
import com.alien.admin.modules.container.service.dto.K8sProjectQueryCriteria;
import com.alien.admin.modules.deploy.domain.DpServerConfig;
import com.alien.admin.utils.ValidationUtil;
import com.alien.admin.utils.FileUtil;
import lombok.RequiredArgsConstructor;
import com.alien.admin.modules.deploy.repository.DpServerConfigRepository;
import com.alien.admin.modules.deploy.service.DpServerConfigService;
import com.alien.admin.modules.deploy.service.dto.DpServerConfigDto;
import com.alien.admin.modules.deploy.service.dto.DpServerConfigQueryCriteria;
import com.alien.admin.modules.deploy.service.mapstruct.DpServerConfigMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import com.alien.admin.utils.PageUtil;
import com.alien.admin.utils.QueryHelp;

import java.sql.Timestamp;
import java.util.List;
import java.util.Map;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.LinkedHashMap;

/**
 * @author zengzhifang
 * @website https://el-admin.vip
 * @description 服务实现
 * @date 2021-09-28
 **/
@Service
@RequiredArgsConstructor
public class DpServerConfigServiceImpl implements DpServerConfigService {

    private final DpServerConfigRepository dpServerConfigRepository;
    private final DpServerConfigMapper dpServerConfigMapper;

    @Override
    public Map<String, Object> queryAll(DpServerConfigQueryCriteria criteria, Pageable pageable) {
        Page<DpServerConfig> page = dpServerConfigRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder), pageable);
        return PageUtil.toPage(page.map(dpServerConfigMapper::toDto));
    }

    @Override
    public List<DpServerConfigDto> queryAll(DpServerConfigQueryCriteria criteria) {
        return dpServerConfigMapper.toDto(dpServerConfigRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder)));
    }

    @Override
    @Transactional
    public DpServerConfigDto findById(Integer id) {
        DpServerConfig dpServerConfig = dpServerConfigRepository.findById(id).orElseGet(DpServerConfig::new);
        ValidationUtil.isNull(dpServerConfig.getId(), "DpServerConfig", "id", id);
        return dpServerConfigMapper.toDto(dpServerConfig);
    }

    @Override
    @Transactional
    public DpServerConfigDto findFirstByProjectIdAndEnv(Integer projectId, String env) {
        DpServerConfig dpServerConfig = dpServerConfigRepository.findFirstByProjectIdAndEnv(projectId, env);
        return dpServerConfigMapper.toDto(dpServerConfig);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public DpServerConfigDto create(DpServerConfig resources) {
        return dpServerConfigMapper.toDto(dpServerConfigRepository.save(resources));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(DpServerConfig resources) {
        DpServerConfig dpServerConfig = dpServerConfigRepository.findById(resources.getId()).orElseGet(DpServerConfig::new);
        ValidationUtil.isNull(dpServerConfig.getId(), "DpServerConfig", "id", resources.getId());
        dpServerConfig.copy(resources);
        dpServerConfigRepository.save(dpServerConfig);
    }

    /**
     * buildParam和DeployParam是在不同的页面上的。
     * 页面保存的时候，只处理这个页面相关的值，另一个值默认为空，表示不操作。
     *
     * @param resources
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveOrUpdate(DpServerConfig resources) {

        DpServerConfig dpServerConfig = dpServerConfigRepository.findFirstByProjectIdAndEnv(resources.getProjectId(), resources.getEnv());
        if (dpServerConfig == null || dpServerConfig.getId() == null) {
            resources.setCreateTime(new Timestamp(System.currentTimeMillis()));
            resources.setUpdateTime(new Timestamp(System.currentTimeMillis()));
            dpServerConfigRepository.save(resources);
            return;
        }
        ValidationUtil.isNull(dpServerConfig.getId(), "DpServerConfig", "id", resources.getId());
        // 不能直接复制resouces的值！因为字段分散在不同的页面上！
        // 如果是修改buildParam
        if(resources.getModifyBuildParam()!=null && resources.getModifyBuildParam()){
            dpServerConfig.setBuildParam(resources.getBuildParam());
        }
        // 如果是修改deployParam
        if(resources.getModifyDeployParam()!=null && resources.getModifyDeployParam()){
            dpServerConfig.setDeployParam(resources.getDeployParam());
        }
        // 如果是修改k8sInstanceId
        if(resources.getModifyK8sInstanceId()!=null && resources.getModifyK8sInstanceId()){
            dpServerConfig.setK8sInstanceId(resources.getK8sInstanceId());
        }
        // 如果是修改k8sInstanceId
        if(resources.getModifyK8sNameSpace()!=null && resources.getModifyK8sNameSpace()){
            dpServerConfig.setK8sNameSpace(resources.getK8sNameSpace());
        }
        dpServerConfig.setUpdateBy(resources.getUpdateBy());
        resources.setUpdateTime(new Timestamp(System.currentTimeMillis()));
        dpServerConfigRepository.save(dpServerConfig);
    }

    @Override
    public void deleteAll(Integer[] ids) {
        for (Integer id : ids) {
            dpServerConfigRepository.deleteById(id);
        }
    }

    @Override
    public void download(List<DpServerConfigDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (DpServerConfigDto dpServerConfig : all) {
            Map<String, Object> map = new LinkedHashMap<>();
            map.put("服务id", dpServerConfig.getProjectId());
            map.put("环境", dpServerConfig.getEnv());
            map.put("构建参数的值，是一个json串", dpServerConfig.getBuildParam());
            map.put("部署参数的值", dpServerConfig.getDeployParam());
            map.put("创建人", dpServerConfig.getCreateBy());
            map.put("修改人", dpServerConfig.getUpdateBy());
            map.put("创建日期", dpServerConfig.getCreateTime());
            map.put("更新时间", dpServerConfig.getUpdateTime());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }

    @Override
    public DpServerConfig findDpServerConfig(K8sProjectQueryCriteria criteria) {
        Long projectId = criteria.getProjectId();
        String env = criteria.getEnv();

        DpServerConfig dpServerConfig = dpServerConfigRepository.findFirstByProjectIdAndEnv(projectId.intValue(), env);
        if (dpServerConfig == null || dpServerConfig.getId() == null) {
            throw new BadRequestException("找不到项目的配置信息");
        }

        return dpServerConfig;
    }
}
